package com.maike.babyname.network;

import android.annotation.SuppressLint;
import android.os.Build;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.maike.babyname.BuildConfig;
import com.maike.babyname.utils.LogUtils;

import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;

import io.reactivex.ObservableTransformer;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class HttpMethods {

    private static final int DEFAULT_TIMEOUT = 60;

    /**
     * 默认地址
     */
    public static String BASE_URL = BuildConfig.SERVER_HOST_MOCK;


    private Retrofit retrofit;


    //构造方法私有
    private HttpMethods() {

        HttpLoggingInterceptor.Logger logger = new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                LogUtils.e("==Logger:" + message);
            }
        };
        HttpLoggingInterceptor log = new HttpLoggingInterceptor(logger);
        log.setLevel(HttpLoggingInterceptor.Level.BODY);


        //手动创建一个OkHttpClient并设置超时时间
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .addInterceptor(new LogInterceptor()) //添加日志输出
                .sslSocketFactory(createSSLSocketFactory())
                .retryOnConnectionFailure(true)//出现错误重新连接
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        if (LogUtils.ENABLE) {
            builder.addInterceptor(log);
        }

        Gson gson = new GsonBuilder().serializeNulls().create();
        retrofit = new Retrofit.Builder()
                .client(builder.build())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(BASE_URL)
                .build();

        if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
            System.setProperty("http.keepAlive", "false");
        }
    }


    public <T> T createAPI(Class<T> clz) {
        return retrofit.create(clz);
    }

    public <T> Subscription toSubscriber(Observable<T> observable, Observer subscriber) {
        return observable
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(subscriber);
    }

    private static class SingletonHolder {
        private static final HttpMethods INSTANCE = new HttpMethods();
    }


    public static HttpMethods getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /**
     * 默认信任所有的证书
     * TODO 最好加上证书认证，主流App都有自己的证书
     *
     * @return
     */
    @SuppressLint("TrulyRandom")
    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory sSLSocketFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new javax.net.ssl.TrustManager[]{new TrustAllManager()},
                    new SecureRandom());
            sSLSocketFactory = sc.getSocketFactory();
        } catch (Exception e) {
            LogUtils.e(e);
        }
        return sSLSocketFactory;
    }


}
